package com.hhit.bigscreenbackmanage.service.impl.aqgl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hhit.bigscreenbackmanage.common.AqglConstants;
import com.hhit.bigscreenbackmanage.dao.aqgl.*;
import com.hhit.bigscreenbackmanage.entity.aqgl.*;
import com.hhit.bigscreenbackmanage.service.aqgl.*;
import com.hhit.bigscreenbackmanage.util.DateUtils;
import com.hhit.bigscreenbackmanage.vo.aqgl.AqglSearchVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @ClassName AqglStatisticsServiceImpl
 * @Description
 * @Author qianchengcheng
 * @Date 2021/7/26
 */
@Service
public class AqglStatisticsServiceImpl implements AqglStatisticsService {

    private static Logger log = LoggerFactory.getLogger(AqglStatisticsServiceImpl.class);

    @Autowired
    private AqglRbService aqglRbService;

    @Autowired
    private AqglFxCountService aqglFxCountService;

    @Autowired
    private AqglZypTjService aqglZypTjService;

    @Autowired
    private AqglRybzService aqglRybzService;

    @Autowired
    private AqglDrrygkTempService aqglDrrygkTempService;

    @Autowired
    private AqglDailyPaperTempService aqglDailyPaperTempService;

    @Autowired
    private AqglJdjcqkService aqglJdjcqkService;

    @Autowired
    private AqglZypTjDao aqglZypTjDao;

    @Autowired
    private AqglDrrygkTempDao aqglDrrygkTempDao;

    @Autowired
    private AqglFxCountDao aqglFxCountDao;

    @Autowired
    private AqglFxDao aqglFxDao;

    @Autowired
    private AqglJdjcqkSblzDao aqglJdjcqkSblzDao;

    @Autowired
    private AqglJdjcqkYcjcDao aqglJdjcqkYcjcDao;

    @Override
    public Map<String, Object> getDayRiskManagement(String cityName) throws Exception {
        log.info("AqglStatisticsServiceImpl.getDayRiskManagement Call Begin,param[cityName:{}]",cityName);
        // 获取在建工程数
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("inBuildingProjectNum",aqglRbService.getInBuildingProjectNum(cityName));
        TAqglFxCount aqglFxCount = aqglFxCountService.getAqglFxCountEntityByParam(cityName);
        if (ObjectUtil.isNotNull(aqglFxCount)){
            resultMap.put("yjdrfx",aqglFxCount.getYjfxzs());
            resultMap.put("yjdgl",StrUtil.isBlank(aqglFxCount.getYjfxdgdwl()) ? "0" : aqglFxCount.getYjfxdgdwl().replace("%",""));
            resultMap.put("ejdrfx",aqglFxCount.getEjfxzs());
            resultMap.put("ejdgl",StrUtil.isBlank(aqglFxCount.getEjfxdgdwl()) ? "0" :aqglFxCount.getEjfxdgdwl().replace("%",""));
            resultMap.put("sanjdrfx",aqglFxCount.getThreelevelfxzs());
            resultMap.put("sanjdgl",StrUtil.isBlank(aqglFxCount.getSjfxdgdwl()) ? "0" : aqglFxCount.getSjfxdgdwl().replace("%",""));
            resultMap.put("sjdrfx",aqglFxCount.getFourlevelfxzs());
            resultMap.put("wjdrfx",aqglFxCount.getWjfxzs());
        }
        return resultMap;
    }

    @Override
    public Map<String, Object> getDayWorkTickets(String cityName) throws Exception {
        log.info("AqglStatisticsServiceImpl.getDayWorkTickets Call Begin,param[cityName:{}]",cityName);
        Map<String,Object> resultMap = new HashMap<>();
        TAqglZypTj aqglZypTj = aqglZypTjService.getAqglZypTjEntityByParam(cityName);
        if (ObjectUtil.isNotNull(aqglZypTj)){
            resultMap.put("totalTickets",aqglZypTj.getZypslZl());
            resultMap.put("totalATickets",aqglZypTj.getApslZs());
            resultMap.put("aTicketsDzx",aqglZypTj.getApslDzx());
            resultMap.put("aTicketsZxz",aqglZypTj.getApslZxz());
            resultMap.put("aTicketYjp",aqglZypTj.getApslYjp());
            resultMap.put("totalBTickets",aqglZypTj.getBpslZs());
            resultMap.put("bTicketDzx",aqglZypTj.getBpslDzx());
            resultMap.put("bTicketZxz",aqglZypTj.getBpslZxz());
            resultMap.put("bTicketYjp",aqglZypTj.getBpslYjp());
        }
        return resultMap;
    }

    @Override
    public Map<String, Object> getDayAnAccount(String cityName) throws Exception {
        log.info("AqglStatisticsServiceImpl.getDayAnAccount Call Begin,param[cityName:{}]",cityName);
        Map<String,Object> resultMap = new HashMap<>();
        List<TAqglRybz> aqglRybzList = aqglRybzService.getAqglRybzsByParam(cityName);
        if (CollectionUtil.isNotEmpty(aqglRybzList)){
            //获取 已上报的日一本账数量
            int hasRepotedNum = aqglRybzList.stream().filter(t->"已报".equals(t.getSfsb())).collect(Collectors.toList()).size();
            resultMap.put("hasRepotedNum",hasRepotedNum);
            // 获取 未上报的日一本账数量
            int unReportNum = aqglRybzList.stream().filter(t->"未报".equals(t.getSfsb())).collect(Collectors.toList()).size();
            resultMap.put("unReportNum",unReportNum);
            int totalReportNum = hasRepotedNum + unReportNum;
            if (totalReportNum == 0){
                resultMap.put("percent",0);
            }else {
                BigDecimal hasRepotedNumBD = new BigDecimal(hasRepotedNum);
                BigDecimal totalReportNumBD = new BigDecimal(totalReportNum);
                resultMap.put("percent",hasRepotedNumBD.divide(totalReportNumBD,2,BigDecimal.ROUND_UP).multiply(BigDecimal.TEN).multiply(BigDecimal.TEN).stripTrailingZeros().toPlainString());
            }
        }
        return resultMap;
    }

    @Override
    public Map<String, Object> getDayPersonControl(String cityName) throws Exception {
        log.info("AqglStatisticsServiceImpl.getDayPersonControl Call Begin,param[cityName:{}]",cityName);
        if(StrUtil.isEmpty(cityName)){
            cityName = "江苏省";
        }
        Map<String,Object> resultMap = new HashMap<>();
        TAqglDrrygkTemp tAqglDrrygkTemp = aqglDrrygkTempService.getAqglDrrygkTempEntity(cityName);
        if (ObjectUtil.isNotNull(tAqglDrrygkTemp)){
            resultMap.put("totalAttendance",tAqglDrrygkTemp.getKqzrs());
            resultMap.put("realTimeOnSitePersonNum",tAqglDrrygkTemp.getSsdcrs());
        }
        return resultMap;
    }

    @Override
    public Map<String, Object> getDailyPaper(String cityName) throws Exception {
        log.info("AqglStatisticsServiceImpl.getDailyPaper Call Begin,param[cityName:{}]",cityName);
        if (StrUtil.isEmpty(cityName)){
            cityName = "江苏省";
        }
        Map<String,Object> resultMap = new HashMap<>();
        TAqglDailyPaperTemp aqglDailyPaperTemp = aqglDailyPaperTempService.getAqglDailyPaperTempEntity(cityName);
        if (ObjectUtil.isNotNull(aqglDailyPaperTemp)){
            resultMap.put("hasReportedNum",aqglDailyPaperTemp.getYsb());
            resultMap.put("unReportNum",aqglDailyPaperTemp.getWsb());
            if ((Integer.parseInt(aqglDailyPaperTemp.getYsb()) + Integer.parseInt(aqglDailyPaperTemp.getWsb())) ==0){
                resultMap.put("percent","0");
            }else {
                BigDecimal hasReportedNumBD = new BigDecimal(aqglDailyPaperTemp.getYsb());
                BigDecimal unReportNumBD = new BigDecimal(aqglDailyPaperTemp.getWsb());
                BigDecimal totalReportNumBD = hasReportedNumBD.add(unReportNumBD);
                resultMap.put("percent",hasReportedNumBD.divide(totalReportNumBD,2,BigDecimal.ROUND_UP).multiply(BigDecimal.TEN).multiply(BigDecimal.TEN).stripTrailingZeros().toPlainString());
            }
        }
        return resultMap;
    }

    @Override
    public Map<String, Object> getSupervisionCheckSituation(String cityName) throws Exception {
        log.info("AqglStatisticsServiceImpl.getSupervisionCheckSituation Call Begin,param[cityName:{}]",cityName);
        Map<String,Object> resultMap = new HashMap<>();
        String lastMonth = DateUtils.beforeMonth48(DateUtils.formateDate(new Date(),"yyyy-MM"));
        // 获取四不两直
        Map<String,Object> param = new HashMap<>();
        param.put("cityName",cityName);
        param.put("datetime",lastMonth);
        List<TAqglJdjcqkSblz> aqglJdjcqkSblzList = aqglJdjcqkSblzDao.getAqglJdjcqkSblzListByParam(param);
        int dcxmNum = 3; int fxdxwt = 17; int wczgNum = 17;
        if (CollectionUtil.isNotEmpty(aqglJdjcqkSblzList)){
            dcxmNum = aqglJdjcqkSblzList.stream().collect(Collectors.groupingBy(TAqglJdjcqkSblz::getJcxm)).size();
            fxdxwt = aqglJdjcqkSblzList.size();
            wczgNum = aqglJdjcqkSblzList.stream().filter(t->"是".equals(t.getSfwczg())).collect(Collectors.toList()).size();
        }
        resultMap.put("sblzDcxm",dcxmNum);
        resultMap.put("sblzFxdxwt",fxdxwt);
        resultMap.put("sblzWczg",wczgNum);
        BigDecimal fxdxwtBD = new BigDecimal(fxdxwt);
        BigDecimal wczgBD = new BigDecimal(wczgNum);
        if (fxdxwtBD.compareTo(BigDecimal.ZERO) == 0){
            resultMap.put("sblzZgbl","100");
        }else {
            resultMap.put("sblzZgbl",wczgBD.divide(fxdxwtBD,2,BigDecimal.ROUND_UP).multiply(BigDecimal.TEN).multiply(BigDecimal.TEN).stripTrailingZeros().toPlainString());
        }
        // 获取远程检查
        List<TAqglJdjcqkYcjc> aqglJdjcqkYcjcList = aqglJdjcqkYcjcDao.getAqglJdjcqkYcjcListByParam(param);
        int ycjcYcjcNum = 154; int ycjcFxdxWtNum = 103; int ycjcWczgNum = 103;
        if (CollectionUtil.isNotEmpty(aqglJdjcqkYcjcList)){
            ycjcYcjcNum = aqglJdjcqkYcjcList.size();
            ycjcFxdxWtNum = aqglJdjcqkYcjcList.stream().filter(t-> !"无".equals(t.getWtms())).collect(Collectors.toList()).size();
            ycjcWczgNum = aqglJdjcqkYcjcList.stream().filter(t->("是".equals(t.getSfwczg()) && !"无".equals(t.getWtms()))).collect(Collectors.toList()).size();
        }
        resultMap.put("ycjcYcjc",ycjcYcjcNum);
        resultMap.put("ycjcFxdxwt",ycjcFxdxWtNum);
        resultMap.put("ycjcWczg",ycjcWczgNum);
        BigDecimal ycjcFxdxwtBD = new BigDecimal(ycjcFxdxWtNum);
        if (ycjcFxdxwtBD.compareTo(BigDecimal.ZERO) == 0){
            resultMap.put("ycjcZgbl","100");
        }else {
            BigDecimal ycjcWczgBD = new BigDecimal(ycjcWczgNum);
            resultMap.put("ycjcZgbl",ycjcWczgBD.divide(ycjcFxdxwtBD,2,BigDecimal.ROUND_UP).multiply(BigDecimal.TEN).multiply(BigDecimal.TEN).stripTrailingZeros().toPlainString());
        }
        resultMap.put("month",LocalDate.now().getMonthValue()-1);
        return resultMap;
    }

    @Override
    public Map<String, Object> getMonthlyRiskCompletion(String cityName) throws Exception {
        log.info("AqglStatisticsServiceImpl.getMonthlyRiskCompletion Call Begin,param[cityName:{}]",cityName);
        if (StrUtil.isEmpty(cityName)){
            cityName = "全省";
        }
        String[] monthArr = new String[]{"01月","02月","03月","04月","05月","06月","07月","08月","09月","10月","11月","12月"};
        // 获取当前年
        LocalDate today = LocalDate.now();
        String currentYear = String.valueOf(today.getYear());
        Map<String,Object> resultMap = new HashMap<>();
        List<Long> monthFinishedDataList = new ArrayList<>();
        List<Long> monthUnFinishDataList = new ArrayList<>();
        for (int i = 0 ; i < monthArr.length ; i++){
            // 拼接时间
            String datetime = currentYear + "-" + monthArr[i].replace("月","");
            TAqglFxCount aqglFxCount = aqglFxCountService.getAqglFxCountRecently(datetime,cityName);
            if (ObjectUtil.isNull(aqglFxCount)){
                monthFinishedDataList.add(0L);
                monthUnFinishDataList.add(0L);
            }else {
                BigDecimal monthFinishedTotalBD = BigDecimal.ZERO;
                BigDecimal monthUnFinishTotalBD = BigDecimal.ZERO;
                monthFinishedTotalBD = monthFinishedTotalBD.add(BigDecimal.valueOf(Long.valueOf(aqglFxCount.getYwg())));
                monthUnFinishTotalBD = monthUnFinishTotalBD.add(BigDecimal.valueOf(Long.valueOf(aqglFxCount.getDkg())).add(BigDecimal.valueOf(Long.valueOf(aqglFxCount.getJxz()))).add(BigDecimal.valueOf(Long.valueOf(aqglFxCount.getZtz()))));
                monthFinishedDataList.add(monthFinishedTotalBD.longValue());
                monthUnFinishDataList.add(monthUnFinishTotalBD.longValue());
            }
        }
        resultMap.put("unFinish",monthUnFinishDataList);
        resultMap.put("hasFinished",monthFinishedDataList);
        resultMap.put("year",LocalDate.now().getYear());
        return resultMap;
    }

    @Override
    public Map<String, Object> getDailyReport(String cityName) throws Exception {
        log.info("AqglStatisticsServiceImpl.getDailyReport Call Begin,param[cityName:{}]",cityName);
        LocalDate localDate = LocalDate.now();
        LocalDate yesterday = localDate.plusDays(-1);
        // 获取二级风险、三级风险、三级风险到岗率 在施工程数
        Map<String,Object> resultMap = new HashMap<>();
        Map<String,Object> responseMap = new HashMap<>();
        responseMap = this.getDayRiskManagement(cityName);
//        this.getDayRiskManagementTj();
//        resultMap.put("ejdrfx", MapUtil.getStr(responseMap,"ejdrfx"));
//        resultMap.put("sanjdrfx",MapUtil.getStr(responseMap,"sanjdrfx"));
//        resultMap.put("sanjdgl",MapUtil.getStr(responseMap,"sanjdgl"));
//        resultMap.put("inBuildingProjectNum",MapUtil.getStr(responseMap,"inBuildingProjectNum"));
        resultMap.put("inBuildingProjectNum",521);
        responseMap.clear();
        responseMap = this.getDayRiskManagementTj(yesterday.toString());
        resultMap.put("ejdrfx",MapUtil.getStr(responseMap,"ejdrfx"));
        resultMap.put("sanjdrfx",MapUtil.getStr(responseMap,"sanjdrfx"));
        resultMap.put("sanjdgl",100);
        responseMap = this.getSupervisionCheckSituation(cityName);
        resultMap.put("sblzDcxm",MapUtil.getStr(responseMap,"sblzDcxm"));
        responseMap.clear();
        responseMap = this.getDayAnAccount(cityName);
//        resultMap.put("percent",MapUtil.getStr(responseMap,"percent"));
        resultMap.put("percent",86);
        // 剩下的当日安全事故、参建人员、“e安全”应用问题数，考勤数据问题数 写死，据说要接e安全，也不知道有没有
        resultMap.put("draqsg",0);
        resultMap.put("cjry",6754);
        resultMap.put("eaqyywts",0);
        resultMap.put("kqsjwts",0);
        resultMap.put("daytime",yesterday.getYear()+"年"+yesterday.getMonthValue()+"月"+yesterday.getDayOfMonth()+"日");
        return resultMap;
    }


    /**********************************根据e安全提供接口获取数据**********************************/

    @Override
    public Map<String, Object> getDayRiskManagementTj(String dataTime) throws Exception {
        return aqglFxCountDao.getDayRiskManagementTj(dataTime);
    }

    @Override
    public PageInfo<TJjResourceDynamicRiskInfo> getDayRiskManagementDetail(JSONObject json) throws Exception {
        int pageNum = !json.containsKey("pageNum") ? 1 : Integer.parseInt(json.get("pageNum").toString());
        int pageSize = !json.containsKey("pageSize") ? 15 : Integer.parseInt(json.get("pageSize").toString());
        PageHelper.startPage(pageNum,pageSize);
        List<TJjResourceDynamicRiskInfo> list = aqglFxDao.getDayRiskManagementDetail(json);
        PageInfo<TJjResourceDynamicRiskInfo> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public JSONObject getDayWorkTicketsTj(String dataTime) throws Exception {
        return aqglZypTjDao.getDayWorkTicketsTj(dataTime);
    }


    @Override
    public PageInfo<TTestZyp> getDayWorkTicketsDetail(JSONObject json) throws Exception {
        int pageNum = !json.containsKey("pageNum") ? 1 : Integer.parseInt(json.get("pageNum").toString());
        int pageSize = !json.containsKey("pageSize") ? 15 : Integer.parseInt(json.get("pageSize").toString());
        PageHelper.startPage(pageNum,pageSize);
        List<TTestZyp> list = aqglZypTjDao.getDayWorkTicketsDetail(json);
        PageInfo<TTestZyp> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public PageInfo<TJjResourcePeakPersonNum> getDayPersonPageInfo(JSONObject json) throws Exception {
        int pageNum = !json.containsKey("pageNum") ? 1 : Integer.parseInt(json.get("pageNum").toString());
        int pageSize = !json.containsKey("pageSize") ? 15 : Integer.parseInt(json.get("pageSize").toString());
        PageHelper.startPage(pageNum,pageSize);
        AqglSearchVo aqglSearchVo = new AqglSearchVo();
        aqglSearchVo.setPageNum(pageNum);
        aqglSearchVo.setPageSize(pageSize);
        aqglSearchVo.setDatetime(json.getString("datetime"));
        List<TJjResourcePeakPersonNum> list = aqglDrrygkTempDao.getAqglDrrygkTempPageInfo(aqglSearchVo);
        list.stream().forEach(t -> {
            if (t.getBuildorgno().equals(AqglConstants.BUILD_ORG_NO_XZ+"")){
                t.setBuildorgname("徐州供电公司");
            }else if (t.getBuildorgno().equals(AqglConstants.BUILD_ORG_NO_CZ+"")){
                t.setBuildorgname("常州供电公司");
            }else if (t.getBuildorgno().equals(AqglConstants.BUILD_ORG_NO_HA+"")){
                t.setBuildorgname("淮安供电公司");
            }else if (t.getBuildorgno().equals(AqglConstants.BUILD_ORG_NO_LYG+"")){
                t.setBuildorgname("连云港供电公司");
            }else if (t.getBuildorgno().equals(AqglConstants.BUILD_ORG_NO_NJ+"")){
                t.setBuildorgname("南京供电公司");
            }else if (t.getBuildorgno().equals(AqglConstants.BUILD_ORG_NO_NT+"")){
                t.setBuildorgname("南通供电公司");
            }else if (t.getBuildorgno().equals(AqglConstants.BUILD_ORG_NO_SZ+"")){
                t.setBuildorgname("苏州供电公司");
            }else if (t.getBuildorgno().equals(AqglConstants.BUILD_ORG_NO_WX+"")){
                t.setBuildorgname("无锡供电公司");
            }else if (t.getBuildorgno().equals(AqglConstants.BUILD_ORG_NO_ZJ+"")){
                t.setBuildorgname("镇江供电公司");
            }else if (t.getBuildorgno().equals(AqglConstants.BUILD_ORG_NO_YZ+"")){
                t.setBuildorgname("扬州供电公司");
            }else if (t.getBuildorgno().equals(AqglConstants.BUILD_ORG_NO_TZ+"")){
                t.setBuildorgname("泰州供电公司");
            }else if (t.getBuildorgno().equals(AqglConstants.BUILD_ORG_NO_YC+"")){
                t.setBuildorgname("盐城供电公司");
            }else if (t.getBuildorgno().equals(AqglConstants.BUILD_ORG_NO_SQ+"")){
                t.setBuildorgname("宿迁供电公司");
            }else if (t.getBuildorgno().equals(AqglConstants.BUILD_ORG_NO_SJSFGS+"")){
                t.setBuildorgname("江苏省电力有限公司建设分公司");
            }
        });
        PageInfo<TJjResourcePeakPersonNum> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public Map<String, Object> getDayPersonControlTj(JSONObject jsonObject) throws Exception {
        log.info("AqglStatisticsServiceImpl.getDayPersonControlTj Call Begin,param[cityName:{}]",jsonObject);
        Map<String,Object> resultMap = new HashMap<>();
        TAqglDrrygkTemp tAqglDrrygkTemp = aqglDrrygkTempService.getAqglDrrygkTempEntity(jsonObject.getString("cityName"));
        if (ObjectUtil.isNotNull(tAqglDrrygkTemp)){
            resultMap.put("totalAttendance",tAqglDrrygkTemp.getKqzrs());
            resultMap.put("realTimeOnSitePersonNum",tAqglDrrygkTemp.getSsdcrs());
        }
        return resultMap;
    }

    @Override
    public JSONArray getMonthlyRiskCompletionTj(String dataTime) throws Exception {
        return aqglFxCountDao.getMonthlyRiskCompletionTj(dataTime);
    }

    @Override
    public List<TJjResourceDynamicRiskInfo> getDayRiskForGis(JSONObject jsonObject) throws Exception {
        return  aqglFxDao.getDayRiskManagementDetail(jsonObject);

    }

    @Override
    public PageInfo<TJjResourceDynamicRiskInfo> getDayRiskInBuildingDetail(JSONObject json) throws Exception {
        int pageNum = !json.containsKey("pageNum") ? 1 : Integer.parseInt(json.get("pageNum").toString());
        int pageSize = !json.containsKey("pageSize") ? 15 : Integer.parseInt(json.get("pageSize").toString());
        PageHelper.startPage(pageNum,pageSize);
        List<TJjResourceDynamicRiskInfo> list = aqglFxDao.getDayRiskInBuildingDetail(json);
        System.out.println(list);
        PageInfo<TJjResourceDynamicRiskInfo> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }


}
